# 1. 多阶段构建：把“编译/下载”与“运行”彻底分开，最终镜像只留运行态文件
FROM openeuler/openeuler:25.03 AS builder

RUN dnf install -y \
        gcc \
        git \
        unzip \
        wget \
        zlib-devel \
    && \
    # --- OpenSSL 编译和安装 ---
    wget -q https://www.openssl.org/source/openssl-1.1.1n.tar.gz  && \
    tar -zxvf openssl-1.1.1n.tar.gz && \
    cd openssl-1.1.1n && \
    ./config --prefix=/build/usr/local/openssl1.1.1 --openssldir=/build/usr/local/openssl1.1.1/ssl shared zlib && \
    make -j$(nproc) && \
    make install && \
    # --- 清理工作 ---
    # 返回上级目录以便删除源码
    cd .. && \
    # 删除 OpenSSL 源码和压缩包
    rm -rf openssl-1.1.1n openssl-1.1.1n.tar.gz && \
    # 清理系统包缓存
    dnf clean all

# --------------------------------------------------
# 2. 运行时阶段：只拷贝构建产物，不再装编译链
FROM openeuler/openeuler:25.03

# 2.1 安装最小运行时依赖
RUN dnf install -y \
        gcc \
        git && \
    dnf remove -y openssl && \
    dnf clean all

# 2.2 把 builder 阶段编译好的 openssl 拷贝进来
COPY --from=builder /build/usr/local/openssl1.1.1 /usr/local/openssl1.1.1
RUN echo '/usr/local/openssl1.1.1/lib' > /etc/ld.so.conf.d/openssl.conf \
    && ldconfig \
    && ln -sf /usr/local/openssl1.1.1/bin/openssl /usr/bin/openssl

# 2.3 拷贝并解压仓颉 SDK + stdx（一条 RUN 完成，减少层）
ENV CANGJIE_HOME=/opt/cangjie
ENV CANGJIE_STDX_PATH=/opt/cangjie/stdx
COPY cangjie-sdk-linux-aarch64-1.0.4.tar.gz \
     cangjie-stdx-linux-aarch64-1.0.4.1.zip /tmp/
RUN set -eux; \
    mkdir -p ${CANGJIE_HOME}; \
    tar -xzf /tmp/cangjie-sdk-linux-aarch64-1.0.4.tar.gz --strip-components=1 -C ${CANGJIE_HOME}; \
    unzip -q /tmp/cangjie-stdx-linux-aarch64-1.0.4.1.zip -d /tmp; \
    mkdir -p ${CANGJIE_STDX_PATH}; \
    mv /tmp/linux_aarch64_llvm ${CANGJIE_STDX_PATH}/; \
    rm -f /tmp/*.tar.gz /tmp/*.zip; \
    # 注册运行时库路径
    echo "${CANGJIE_HOME}/runtime/lib/linux_aarch64_llvm" > /etc/ld.so.conf.d/cangjie.conf; \
    ldconfig

# 2.4 环境变量 & PATH
ENV PATH=${CANGJIE_HOME}/bin:${CANGJIE_HOME}/tools/bin:$PATH
ENV LIBRARY_PATH=/usr/lib/gcc/aarch64-openEuler-linux/12:$LIBRARY_PATH
ENV LD_LIBRARY_PATH=/usr/lib/gcc/aarch64-openEuler-linux/12:$LD_LIBRARY_PATH

# 2.5 验证
RUN cjc --version

# 2.6 工作目录 & 默认 shell
WORKDIR /app
CMD ["/bin/bash"]